package activity.setting.PlanVideo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.TextView;
import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import activity.AllAdapter.PlanDetailAdapter;
import base.HiActivity;
import bean.MyCamera;
import bean.TimeArrayBean;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import custom.TimeDomainView;

public class PlanVideoDetailActivity extends HiActivity implements View.OnClickListener, ICameraIOSessionCallback {
    TimeArrayBean mBean;
    @BindView(R.id.title) TitleView mTitle;
    @BindView(R.id.lv_period) ListView lv_period;
    private PlanDetailAdapter mAdapter;

    @BindView(R.id.view_td) TimeDomainView view_td;
    @BindView(R.id.tv_add_time) TextView tv_add_time;
    private ArrayList<String> mAdapterData;
    private MyCamera mMyCamera;
    private HiChipDefines.HI_P2P_QUANTUM_TIME quantum_time;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_plan_video_detail;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        initViewAndData();
        setOnListeners();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMyCamera != null) {
            mMyCamera.registerIOSessionListener(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMyCamera != null) {
            mMyCamera.unregisterIOSessionListener(this);
        }
    }

    private void setOnListeners() {
        tv_add_time.setOnClickListener(this);
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("bean", mBean);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }

    private void initViewAndData() {
        String title = " ";
        switch (mBean.title) {
            case 0:
                title = getString(R.string.sunday);
                break;
            case 1:
                title = getString(R.string.monday);
                break;
            case 2:
                title = getString(R.string.tuesday);
                break;
            case 3:
                title = getString(R.string.wednesday);
                break;
            case 4:
                title = getString(R.string.thursday);
                break;
            case 5:
                title = getString(R.string.friday);
                break;
            case 6:
                title = getString(R.string.saturday);
                break;
        }
        mTitle.setTitle(title);
        mTitle.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        mTitle.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        Intent intent = new Intent();
                        intent.putExtra("bean", mBean);
                        setResult(Activity.RESULT_OK, intent);
                        finish();
                        break;
                }
            }
        });

        lv_period.addHeaderView(new ViewStub(this));
        if (mBean.mIsAllDay) {
            mBean.arrs.clear();
            mBean.arrs.add("00:00-23:59");
        }
        mAdapterData = mBean.arrs;
        mAdapter = new PlanDetailAdapter(PlanVideoDetailActivity.this, mAdapterData);
        lv_period.setAdapter(mAdapter);

        view_td.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                view_td.post(new Runnable() {
                    @Override
                    public void run() {
                        view_td.drawTimeDomain(mBean);
                    }
                });
            }
        });
        mAdapter.setOnDeleteListeners(new PlanDetailAdapter.OnDeleteListeners() {
            @Override
            public void onDelete(int position) {
                if (position <= mBean.getArrs().size()) {
                    if (mBean.getArrs().size() > 0) {
                        mBean.getArrs().remove(position);
                        mAdapter.notifyDataSetChanged();
                    }
                    if (mBean.mIsAllDay) {
                        mBean.mIsAllDay = false;
                    }
                    view_td.drawTimeDomain(mBean);
                    handApplication(mBean);
                }
            }
        });
    }

    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

    private void handApplication(TimeArrayBean bean) {
        int i = bean.getTitle();
        for (int j = 0; j < 48; j++) {
            quantum_time.sDayData[i][j] = 78;//关
            if (bean.mIsAllDay) {
                quantum_time.sDayData[i][j] = 80;
                continue;
            }
            if (bean.getArrs() != null && bean.getArrs().size() < 1 && !bean.mIsAllDay) {
                quantum_time.sDayData[i][j] = 78;
                continue;
            }
            for (String strArr : bean.arrs) {
                String[] strings = strArr.split("-");
                String strStar = strings[0];
                String strEnd = strings[1];
                try {
                    int indexStar = dateToMinute(sdf.parse(strStar)) / 30;
                    int indexEnd = dateToMinute(sdf.parse(strEnd)) / 30 - 1;
                    if (strEnd.equals("23:59")) {
                        indexEnd = 47;
                    }
                    if (j >= indexStar && j <= indexEnd) {
                        quantum_time.sDayData[i][j] = 80;//开
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_REC_AUTO_SCHEDULE, quantum_time.parseContent());
    }

    private int dateToMinute(Date date) {
        return date.getHours() * 60 + date.getMinutes();
    }


    private void getIntentData() {
        mBean = getIntent().getParcelableExtra("bean");
        String str_uid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        if (!TextUtils.isEmpty(str_uid)) {
            for (MyCamera camera : HiDataValue.CameraList) {
                if (str_uid.equals(camera.getUid())) {
                    this.mMyCamera = camera;
                    break;
                }
            }
        }
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_REC_AUTO_SCHEDULE, new byte[0]);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_add_time:
                Intent intent = new Intent(PlanVideoDetailActivity.this, AddTimeDomainActivity.class);
                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mMyCamera.getUid());
                ArrayList<TimeArrayBean> beans = new ArrayList<>();
                beans.add(mBean);
                intent.putParcelableArrayListExtra("beans", beans);
                startActivityForResult(intent, 119, 1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 119:
                    ArrayList<TimeArrayBean> beans = data.getParcelableArrayListExtra("beans");
                    if(beans!=null&&beans.size()>0){
                        mBean = beans.get(0);
                        mAdapterData.clear();
                        mAdapterData.addAll(beans.get(0).arrs);
                        mAdapter.notifyDataSetChanged();
                    }
                    break;


            }
        }
    }

    @Override
    public void receiveSessionState(HiCamera hiCamera, int i) {

    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != mMyCamera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = Message.obtain();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == 0) {//成功
                        handIOCTRLSuccess(msg);
                    } else {//失败
                    }
                    break;
            }
        }
    };

    private void handIOCTRLSuccess(Message msg) {
        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray(HiDataValue.EXTRAS_KEY_DATA);
        switch (msg.arg1) {
            case HiChipDefines.HI_P2P_GET_REC_AUTO_SCHEDULE:
                quantum_time = new HiChipDefines.HI_P2P_QUANTUM_TIME(data);
                break;
            case HiChipDefines.HI_P2P_SET_REC_AUTO_SCHEDULE:
                //dismissjuHuaDialog();
                break;
        }
    }


}
